package artid.com.arttogoa;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import artid.com.arttogoa.app.ArtWorkApp;
import artid.com.arttogoa.barcode.Cache;
import artid.com.arttogoa.db.DataKeeper;
import artid.com.arttogoa.parser.ClasslistParse;
import artid.com.arttogoa.parser.MyWalletParser;
import artid.com.arttogoa.parser.OneStateParser;
import artid.com.arttogoa.task.CallbackSky;
import artid.com.arttogoa.util.AlumAlert;
import artid.com.arttogoa.util.AppUtil;
import artid.com.arttogoa.util.CountDownTimer_Util;
import artid.com.arttogoa.util.RegexUtil;
import artid.com.arttogoa.view.MyEditText;
import artid.com.arttogoa.volley.VolleyBasic;
import artid.com.arttogoa.volley.VolleyCallback;
import artid.com.arttogoa.volley.VolleyData;
import artid.com.arttogoa.volley.VolleyMap;
import com.android.volley.VolleyError;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

/**
 * 
 *    
 * 项目名称：ArtworkArtA   
 * 类名称   ：Withdrawals_Activity   
 * 类描述   ：提现页面   
 * 创建人   ：耿卫斌   
 * 创建时间：2016-7-19 下午3:09:37   
 *
 */
public class Withdrawals_Activity extends BaseActivity implements OnClickListener{
	private Context mContext;
	private MyEditText nameEd,accountNumberEd,verificationNumberEd,priceEd;
	private TextView bankName_tv,balance;
	private Button get_codeBtn,submitBtn;
	private String price;//余额
	private List<ClasslistParse.Classlist> list_bank;
	private Boolean isPricePass=false;//价格是否通过
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_withdrawals);
		mContext=Withdrawals_Activity.this;
		setContent(this, getIntent());
		initView();
	}

	private void initView(){
		mTittle.setText("提现");
		setBack();
		price=getIntent().getStringExtra("price");
		nameEd=(MyEditText) findViewById(R.id.withdrawals_nameEd);
		nameEd.addTextChangedListener(mTextChangedListener);
		bankName_tv=(TextView) findViewById(R.id.withdrawals_banckName);
		bankName_tv.addTextChangedListener(mTextChangedListener);
		bankName_tv.setOnClickListener(this);
		accountNumberEd=(MyEditText) findViewById(R.id.withdrawals_accountNumberEd);
		accountNumberEd.addTextChangedListener(mTextChangedListener);
		verificationNumberEd=(MyEditText) findViewById(R.id.withdrawals_verificationNumberEd);
		verificationNumberEd.addTextChangedListener(mTextChangedListener);
		get_codeBtn=(Button) findViewById(R.id.withdrawals_get_code);
		get_codeBtn.setOnClickListener(this);
		priceEd=(MyEditText) findViewById(R.id.withdrawals_priceEd);
		priceEd.addTextChangedListener(mPriceListener);
		balance=(TextView) findViewById(R.id.withdrawals_balance);
		balance.setText("可用账号余额："+price);
		submitBtn=(Button) findViewById(R.id.withdrawals_submit);
		submitBtn.setOnClickListener(this);
		submitBtn.setEnabled(false);
		submitBtn.setBackgroundResource(R.drawable.zjm_bg_dl);
		getBank();
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.withdrawals_banckName:
			// 获取银行
			//防止软键盘是开启的
			FilingQuickSell_Activity.hideSoftInput(this);
			AlumAlert.initAlertDialog(this,list_bank, bankCall);
			break;
		case R.id.withdrawals_get_code:
			//获取验证码
			getVerificationNumber();
			break;
		case R.id.withdrawals_submit:
			//确认提现
			postWithdrawals();
			break;

		default:
			break;
		}
	}

	/**
	 * 获取银行信息
	 */
	private void getBank(){
		ClasslistParse bean = (ClasslistParse) DataKeeper.readSerializable(mContext, ClasslistParse.class);
		if (bean != null) {
			list_bank = bean.getBank_list();
		} else {
			list_bank = new ArrayList<ClasslistParse.Classlist>();
		}
	}

	CallbackSky bankCall = new CallbackSky() {

		@Override
		public void callBack(int index) {
			// TODO Auto-generated method stub
			bankName_tv.setText(list_bank.get(index).getName());
		}
	};

	/**
	 * 获取验证码
	 */
	private CountDownTimer_Util timer = new CountDownTimer_Util(60000, 1000) {

		@Override
		public void onTick(long millisUntilFinished) {
			get_codeBtn.setText((millisUntilFinished / 1000) + "秒后可重发");
			get_codeBtn.setClickable(false);
		}

		@Override
		public void onFinish() {
			get_codeBtn.setEnabled(true);
			get_codeBtn.setClickable(true);
			get_codeBtn.setText("获取验证码");
		}
	};

	/**
	 * 对价格输入的监听
	 */
	TextWatcher mPriceListener = new TextWatcher() {  
		private CharSequence temp;  
		@Override  
		public void onTextChanged(CharSequence s, int start, int before, int count) {  
			// TODO Auto-generated method stub  
			temp = s;  
		}  

		@Override  
		public void beforeTextChanged(CharSequence s, int start, int count,  
				int after) {  
			// TODO Auto-generated method stub  
			//		          mTextView.setText(s);//将输入的内容实时显示  
		}  

		@Override  
		public void afterTextChanged(Editable s) {  
			// TODO Auto-generated method stub   
			if(!StringUtils.isEmpty(priceEd.getText().toString())){
				if(Integer.parseInt(priceEd.getText().toString())==0){
					priceEd.setText("");
					showToast("提现金额不能以0开头,请重新填写");
					return;
				}
				if(StringConvertInt(price)<StringConvertInt(priceEd.getText().toString())){
					showToast("金额已超过可提现金额");
					isPricePass=false;
				}else {
					if(StringConvertInt(priceEd.getText().toString())!=0){
						isPricePass=true;
					}else{
						isPricePass=false;
					}
				}
			}else{
				isPricePass=false;
			}
			conditionJudge();
		}  
	};  

	/**
	 * 对EditText/TextView监听
	 */
	TextWatcher mTextChangedListener = new TextWatcher() {  
		private CharSequence temp;  
		@Override  
		public void onTextChanged(CharSequence s, int start, int before, int count) {  
			// TODO Auto-generated method stub  
			temp = s;  
		}  

		@Override  
		public void beforeTextChanged(CharSequence s, int start, int count,  
				int after) {  
			// TODO Auto-generated method stub  
			//		          mTextView.setText(s);//将输入的内容实时显示  
		}  

		@Override  
		public void afterTextChanged(Editable s) {  
			// TODO Auto-generated method stub   
			//对按钮的判断是否可用
			conditionJudge();
		}  
	};  

	/**
	 * 条件判断
	 */
	private void conditionJudge(){
		if(!StringUtils.isEmpty(nameEd.getText().toString()) && !StringUtils.isEmpty(bankName_tv.getText().toString()) &&
				RegexUtil.isBankCard(accountNumberEd.getText().toString()) && !StringUtils.isEmpty(verificationNumberEd.getText().toString()) &&
				isPricePass==true){
			submitBtn.setEnabled(true);
			submitBtn.setBackgroundResource(R.drawable.red_frame);
		}else{
			submitBtn.setEnabled(false);
			submitBtn.setBackgroundResource(R.drawable.zjm_bg_dl);
		}
	}

	/**
	 * String类型转换为Int类型(不分0.0，0) 这个方法提高了Double的准确性但是得到值就会成为 例子1.00变为100
	 * 
	 * @param string
	 * @return
	 */
	public int StringConvertInt(String money) {
		DecimalFormat df;
		df = new DecimalFormat("###.00");
		String m = df.format(Double.valueOf(money));
		String str = m.substring(0, m.indexOf("."))
				+ m.substring(m.indexOf(".") + 1);
		int moneys = Integer.parseInt(str);
		return moneys;
	}

	/**
	 * 获取验证码
	 */
	private void getVerificationNumber(){
		VolleyBasic.getInstance(this).post(
				Cache.sendresetcode,
				VolleyMap.getInstance().sendresetcode(AppUtil.getUser().getMobile()), OneStateParser.class,
				new VolleyCallback() {

					@Override
					public void onSuccess(VolleyData vd) {
						System.out.print(vd.getJson());
						//获取验证码成功
						timer.start();
					}

					@Override
					public void onError(VolleyError volleyError) {
						timer.cancel();		
						timer.onFinish();
						showToast("获取验证码失败");
					}
				});
	}

	/**
	 * 提现
	 * 	卖家用户ID token
		银行名称	pdc_bank_name
		账户姓名	username
		提现账号	topup_account
		提现金额	topup_sum
		短线验证码 code
	 */
	private void postWithdrawals(){
		VolleyBasic.getInstance(this).post(true,false,
				Cache.withdrawDeposit,
				VolleyMap.getInstance().withdrawDeposit(bankName_tv.getText().toString(),nameEd.getText().toString(),
						accountNumberEd.getText().toString(),priceEd.getText().toString(),verificationNumberEd.getText().toString()),
						OneStateParser.class, new VolleyCallback() {
			@Override
			public void onSuccess(VolleyData vd) {
				Log.d("log", vd.toString());
				OneStateParser bean=(OneStateParser) vd.getData();
				if("1".equals(bean.getState())){
					getBalance();
				}else{
					showToast("提现失败，请稍后重试");
				}
			}

			@Override
			public void onError(VolleyError volleyError) {
				// TODO Auto-generated method stub

			}
		});
	}

	/**
	 * 获取余额
	 */
	private void getBalance(){
		VolleyBasic.getInstance(this).post(false,true,
				Cache.myPurse,
				VolleyMap.getInstance().myPurse(),
				MyWalletParser.class, new VolleyCallback() {
			@Override
			public void onSuccess(VolleyData vd) {
				Log.d("log", vd.toString());
				MyWalletParser bean=(MyWalletParser) vd.getData();
				ArtWorkApp.getInstance().addActivity(Withdrawals_Activity.this);
				Intent i=new Intent(mContext,WithdrawalsInfo_Activity.class);
				i.putExtra("banckName", bankName_tv.getText().toString());
				i.putExtra("accountNumber", accountNumberEd.getText().toString());
				i.putExtra("withdrawals", priceEd.getText().toString());
				//获取提现后的余额并且保存起来
				AppUtil.getUser().setAvailable_predeposit(bean.getAvailable_predeposit());
				//通知刷新个人信息
				MainActivity.isRefreshPersonal=true;
				startActivity(i);
			}

			@Override
			public void onError(VolleyError volleyError) {
				// TODO Auto-generated method stub

			}
		});
	}

}
